package com.webridge.plm.processor;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.FormResult;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import wt.fc.IdentityHelper;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartMasterIdentity;
import wt.pom.PersistenceException;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;

import com.ptc.windchill.enterprise.part.forms.CreatePartAndCADDocFormProcessor;
import com.webridge.plm.constants.IBAConstant;

public class CustomCreatePartProcessor extends CreatePartAndCADDocFormProcessor {

	private static final Logger LOGGER = LogR
			.getLogger(CustomCreatePartProcessor.class.getName());

	@Override
	public FormResult postProcess(NmCommandBean nmcommandbean,
            List<ObjectBean> objects) throws WTException {
        FormResult result = null;

        LOGGER.debug("create part process run");
        LOGGER.debug("nmCommandbean:" + nmcommandbean + ",objects:"
                + objects.size());
        WTPart part = null;
        ObjectBean bean = objects.get(0);
        part = (WTPart) bean.getObject();
        if (part == null)
            return result;
        Map map = nmcommandbean.getText();
        Object[] keys = map.keySet().toArray();
        String numberPrefix = "";
        for (Object oneSet : keys) {
            if (((String) oneSet).contains(IBAConstant.IBA_NUMBERPREFIX)) {
                numberPrefix = (String) map.get(oneSet);
                break;
            }
        }
        LOGGER.debug("create processor inputText:" + map);
        LOGGER.debug("NumberPrefix:" + numberPrefix);

        LOGGER.debug(nmcommandbean.getSelected());
        LOGGER.debug(nmcommandbean.getTextArea());
        String newNumber = getNumberSequence(numberPrefix.trim());
        if (newNumber.length() != 3) {
            LOGGER.debug("doOperation new Number:" + newNumber + ",Part Number: " + part.getNumber());
            WTPartMaster partMaster = (WTPartMaster) part.getMaster();
            WTPartMasterIdentity docmasteridentity = (WTPartMasterIdentity) partMaster
                    .getIdentificationObject();
            try {
                docmasteridentity.setNumber(newNumber);
            } catch (WTPropertyVetoException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            partMaster = (WTPartMaster) IdentityHelper.service.changeIdentity(partMaster, docmasteridentity);
        }
        result = super.postProcess(nmcommandbean, objects);
        return result;
    }

	@Override
	public FormResult doOperation(NmCommandBean nmcommandbean,
			List<ObjectBean> objects) throws WTException {
		LOGGER.debug("bhss CreatePartProcessor is coming");

		return super.doOperation(nmcommandbean, objects);
	}

	/**
	 * 
	 * @param numberPrefix
	 * @return
	 * @throws PersistenceException
	 * @throws WTException
	 */
	public static String getNumberSequence(String numberPrefix) throws PersistenceException, WTException{
	    
	    //precheck the numberPrefix format
        String regex3 = "\\d{4} \\d{3}";
        String regex6 = "\\d{4}";
        Pattern p3 = Pattern.compile(regex3);
        Pattern p6 = Pattern.compile(regex6);
        boolean match3 = p3.matches(regex3, numberPrefix);
        boolean match6 = p6.matches(regex6, numberPrefix);
        if (!match3 && !match6) {
            throw new WTException("Number prefix format error,should be like:'7069 102' or '7069'");
        }
        
	    
	    //get sequence of numberPrefix
	    
	    String result = "";
	    String suffix = "";
        boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
        try {
            WTPartMaster partMaster = null;
            QuerySpec querySpec = new QuerySpec(WTPartMaster.class);
            SearchCondition searchCondition = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER,
                    SearchCondition.LIKE, numberPrefix+"%", false);
            querySpec.appendSearchCondition(searchCondition);
            OrderBy orderBy = new OrderBy(new ClassAttribute(WTPartMaster.class, WTPartMaster.NUMBER), true);
            querySpec.appendOrderBy(orderBy);
            QueryResult queryResult = PersistenceHelper.manager.find(querySpec);
            while (queryResult.hasMoreElements()) {
                partMaster = (WTPartMaster) queryResult.nextElement();
/*                QueryResult queryResult2 = VersionControlHelper.service.allVersionsOf(partMaster);
                if (queryResult2.hasMoreElements()) {
                    part = (WTPart) queryResult2.nextElement();
                    
                }*/
                break;
            }
            if(partMaster!=null){
                //7069 818 001
                String maxPartNumber = partMaster.getNumber();
                if(maxPartNumber.length()==12){
                    String currentSeq = maxPartNumber.substring(9);
                    if(Integer.parseInt(currentSeq)<999){
                        suffix = startAddZero(String.valueOf(Integer.parseInt(currentSeq)+1),3);
                    }else{
                        throw new WTException("sequence overflow:" + currentSeq);
                    }
                }else{
                    throw new WTException("number format wrong:" + maxPartNumber);
                }
                
            }
 
        } finally {
            SessionServerHelper.manager.setAccessEnforced(enforce);
        }
    
	    
	    if("".equals(suffix))
	        suffix = "001";
	        result  = numberPrefix + " " + suffix;
	    return result;
	    
	    
	}
    public static String startAddZero(String str,int length) {
        if(str.length()<length) {
            int addLength = length - str.length();
            String addStr = "";
            for(int i =0 ;i<addLength;i++) {
                addStr += "0";
            }
            return addStr + str;
        }else {
            return str;
        }
    }
    public static void main(String[] args) throws WTException {
            //7069 818 001
            String maxPartNumber = "7069 818 001";
            if(maxPartNumber.length()==12){
                String currentSeq = maxPartNumber.substring(9);
                if(Integer.parseInt(currentSeq)<999){
                   String suffix = startAddZero(String.valueOf(Integer.parseInt(currentSeq)+1),3);
                  System.out.println("suffix:" + suffix);
                }else{
                    throw new WTException("sequence overflow:" + currentSeq);
                }
            }else{
                throw new WTException("number format wrong:" + maxPartNumber);
            }
            
            
            String numberPrefix = "1212 311";
            String regex = "\\d{4} \\d{3}";
            Pattern p = Pattern.compile(regex);
            boolean match = p.matches(regex, numberPrefix);
            System.out.println("Match:" + match);
            
    }
}
